import { getDictionaryList, listCategoryAndLabelApi } from "@/api/dictionary";
import { defineStore } from "pinia";
import { computed, ref } from "vue";

export const useDictionaryStore = defineStore("dictionaryStore", () => {
  type dictionaryModel = {
    category: string;
    code: string;
    createBy: string;
    createTime: string;
    id: string;
    iflag: number;
    isTreelist: number;
    name: string;
    parentCode: string;
    parentId: string;
    remark: string;
    theOrder: number;
    treeLevel: number;
    updateBy: string;
    updateTime: string;
  };

  type dictionaryCategoryModel = {
    basicCategories: BasicCategory[];
    specialCategories: BasicCategory[];
    labels: Label[];
  };

  interface BasicCategory {
    id: string;
    standardName: string;
    standardType: string;
    standardTypeValue: StandardTypeValue;
    standardLevel: string;
    standardLevelValue: StandardLevelValue;
    pid: string;
    weight: number;
    remark: null | string;
    hasChosen: boolean;
    children: BasicCategory[];
  }

  enum StandardLevelValue {
    专用 = "专用",
    基础 = "基础",
    父级 = "父级",
    通用 = "通用",
  }

  enum StandardTypeValue {
    专题 = "专题",
    基础 = "基础",
  }

  interface Label {
    type: string;
    typeName: string;
    options: Option[];
  }

  interface Option {
    id: string;
    type: number;
    name: string;
    weight: number;
    remark: null;
  }

  const dictionaryList = ref<dictionaryModel[]>([]);
  const dictionaryCategory = ref<dictionaryCategoryModel>(null);

  const initDictionary = async () => {
    await getDictionaryList({
      pageIndex: 1,
      pageSize: 1000,
    }).then(res => {
      console.log(res.data.list);
      dictionaryList.value = res.data.list;
    });
  };

  const initCategory = async () => {
    await listCategoryAndLabelApi("").then(res => {
      dictionaryCategory.value = res.data;
    });
  };

  const getDictionaryByCode = computed(() => {
    return (code: string) => {
      if (!Array.isArray(dictionaryList.value)) {
        console.warn("dictionaryList.value is not an array");
        return [];
      }
      return dictionaryList.value.filter(val => val.parentCode === code).sort((a, b) => a.theOrder - b.theOrder);
    };
  });

  const getDictionaryName = computed(() => {
    return (parentCode: string, code: string) => {
      return dictionaryList.value.find(val => val.parentCode === parentCode && val.code === code)?.name;
    };
  });

  return {
    initDictionary,
    initCategory,
    getDictionaryByCode,
    getDictionaryName,
    dictionaryCategory,
  };
});
